from euler.context import Context

from apitest.engine.logging import logger


class RPCError(Exception):
    def __init__(self, code, message):
        self.code = code
        self.message = message
        super(RPCError, self).__init__('rpc request error, code: %s, message: %s' % (code, message))


def rpc_response_error_middleware(ctx: Context, *args, **kwargs):
    resp = ctx.next(*args, **kwargs)
    if resp.BaseResp and resp.BaseResp.StatusCode != 0:
        raise RPCError(resp.BaseResp.StatusCode, resp.BaseResp.StatusMessage)
    return resp


def rpc_log_middleware(ctx: Context, req, *args, **kwargs):
    """
    增加日志
    :type ctx: Context
    :param req
    """
    # logger.info(ctx.url)  # 协议，psm信息 基本信息
    # logger.info(ctx.local)
    logger.info("logid is %s, runtime env is %s" % (ctx.persistent.get("logid"), ctx.persistent.get("env")))
    logger.info("[%s] request: %s" % (ctx.name, req))
    resp = ctx.next(req, *args, **kwargs)
    logger.info("[%s] response data: %s" % (ctx.name, resp))
    return resp
